package com.ruoyi.project.appConnector;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.page.BaseQuery;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.tree.TreeUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.configureSystem.domain.*;
import com.ruoyi.project.configureSystem.domain.vo.VStationVO;
import com.ruoyi.project.configureSystem.service.ICStationService;
import com.ruoyi.project.configureSystem.service.ISysAreaService;
import com.ruoyi.project.configureSystem.service.IVStationService;
import com.ruoyi.project.orderSystem.domain.OrderStation;
import com.ruoyi.project.orderSystem.domain.OrderStationItem;
import com.ruoyi.project.orderSystem.domain.WorkOrder;
import com.ruoyi.project.orderSystem.domain.vo.OrderStationItemVO;
import com.ruoyi.project.orderSystem.domain.vo.WorkOrderVO;
import com.ruoyi.project.orderSystem.service.IOrderStationItemService;
import com.ruoyi.project.orderSystem.service.IOrderStationService;
import com.ruoyi.project.orderSystem.service.IWorkOrderService;
import com.ruoyi.project.propertySystem.domain.InspectItem;
import com.ruoyi.project.propertySystem.domain.InspectItemRecord;
import com.ruoyi.project.propertySystem.domain.InspectRecord;
import com.ruoyi.project.propertySystem.domain.ItemRecordPic;
import com.ruoyi.project.propertySystem.domain.vo.InspectItemRecordVO;
import com.ruoyi.project.propertySystem.domain.vo.InspectRecordVO;
import com.ruoyi.project.propertySystem.service.IInspectItemRecordService;
import com.ruoyi.project.propertySystem.service.IInspectItemService;
import com.ruoyi.project.propertySystem.service.IInspectRecordService;
import com.ruoyi.project.propertySystem.service.IItemRecordPicService;
import com.ruoyi.project.propertySystem.service.impl.InspectItemRecordServiceImpl;
import com.ruoyi.project.query.InspectRecordQuery;
import com.ruoyi.project.query.WorkOrderQuery;
import com.ruoyi.project.reportSystem.domain.AttendanceRecord;
import com.ruoyi.project.reportSystem.service.IAttendanceRecordService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * Created by huaxin15355 on 2020/5/17.
 * APP接口
 */
@RestController
@RequestMapping("/app/workorder")
public class AppWorkOrderController {
    @Autowired
    private IWorkOrderService iWorkOrderService;
    @Autowired
    private IVStationService ivStationService;
    @Autowired
    private IOrderStationService iOrderStationService;
    @Autowired
    private IOrderStationItemService iOrderStationItemService;
    @Autowired
    private IInspectRecordService inspectRecordService;
    @Autowired
    private IAttendanceRecordService attendanceRecordService;
    @Autowired
    private IInspectItemService iInspectItemService;
    @Autowired
    private IItemRecordPicService iItemRecordPicService;
    @Autowired
    private IInspectItemRecordService iInspectItemRecordService;
    @Autowired
    private ISysAreaService areaService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ICStationService cStationService;
    @Autowired
    private TreeUtils treeUtils;
    /**
     * app端负责人工单(分页)
     */
    @PostMapping("/listExecutorAppWorkOrder")
    public AjaxResult listExecutorAppWorkOrder(@RequestBody WorkOrderQuery workOrderQuery)
    {
        PageHelper.startPage(workOrderQuery.getPageNum(),workOrderQuery.getPageSize());
        List<WorkOrderVO>  workOrderVOList =iWorkOrderService.listExecutorAppWorkOrder(workOrderQuery);
        return AjaxResult.success(new PageInfo<>(workOrderVOList));
    }

    /**
     * 根据工单id获取工单信息
     */
    @GetMapping("/getOrderByOrderId")
    public AjaxResult getOrderByOrderId(@RequestParam Long orderId)
    {
        WorkOrder workOrder = iWorkOrderService.selectWorkOrderDetailById(orderId);
        return AjaxResult.success(workOrder);
    }

    /**
     * 根据工单id获取站点列表
     */
    @GetMapping("/getOrderStationByOrderId")
    public AjaxResult getOrderStationByOrderId(@RequestParam Long orderId)
    {
        OrderStation orderStation = new OrderStation();
        orderStation.setOrderId(orderId);
        List<OrderStation> orderStations = iOrderStationService.selectOrderStationList(orderStation);
        return AjaxResult.success(orderStations);
    }

    /**
     * 巡检站点新增
     */
    @PostMapping("/saveOrderItem")
    public AjaxResult saveOrderItem(@RequestBody OrderStationItem orderStationItem)
    {
        int i = iOrderStationItemService.saveOrderItem(orderStationItem);
       return AjaxResult.success(i);
    }

    /**
     * 工单站点巡检项列表
     */
    @GetMapping("/listItemByOrderStationId")
    public AjaxResult listItemByOrderStationId(@RequestParam Long orderStationId)
    {
        Optional.ofNullable(orderStationId).orElseThrow(()->new BaseException("参数异常"));
        OrderStationItem orderStationItem = new OrderStationItem();
        orderStationItem.setOrderStationId(orderStationId);
        List<OrderStationItem> orderStationItems = iOrderStationItemService.selectOrderStationItemList(orderStationItem);
        return AjaxResult.success(orderStationItems);
    }

    /**
     * 工单站点巡检项，暂只考虑一项
     */
    @GetMapping("/getOrderStationItemByOrderStationId")
    public AjaxResult getOrderStationItemByOrderStationId(@RequestParam Long orderStationId)
    {
        Optional.ofNullable(orderStationId).orElseThrow(()->new BaseException("参数异常"));
        OrderStationItemVO orderStationItemVO = iOrderStationItemService.getOrderStationItemByOrderStationId(orderStationId);
        return AjaxResult.success(orderStationItemVO);
    }


    /**
     * app端根据工单主键id修改工单的状态
     */
    @GetMapping("/updateOrderState")
    @CrossOrigin
    public AjaxResult updateOrderState(Long oderzjid){
        AjaxResult ajaxResult = AjaxResult.success();
        WorkOrder workOrder=new WorkOrder();
        workOrder.setId(oderzjid);
        workOrder.setOrderStatus(1);//状态改为1 进行中
        int i=iWorkOrderService.updateWorkOrderByID(workOrder);
        if (i>0){
            return ajaxResult.success("修改成功");
        }else {
            return ajaxResult.error("修改失败");
        }

    }

    /**
     * 用户关联的站点（分页）
     */
    @PostMapping("/appUserStationList")
    public AjaxResult appUserStationList(@RequestBody BaseQuery baseQuery)
    {
        PageHelper.startPage(baseQuery.getPageNum(), baseQuery.getPageSize());
        List<VStation> stationByRole = ivStationService.getStationByRole(new VStation());
        return AjaxResult.success(new PageInfo<>(stationByRole));
    }

    /**
     * 根据经纬度查附近站点
     */
    @GetMapping("/listStationByLocation")
    public AjaxResult listStationByLocation(@RequestParam String longitude,@RequestParam String latitude)
    {
        Optional.ofNullable(longitude).orElseThrow(()->new  BaseException("参数缺失"));
        Optional.ofNullable(latitude).orElseThrow(()->new  BaseException("参数缺失"));
//        List<VStation> vStationList = ivStationService.selectVStationList(new VStation());
//        return AjaxResult.success(vStationList);
        List<VStationVO> vStationList =ivStationService.selectStationByLocation(longitude,latitude);
        return AjaxResult.success(vStationList);
    }


    /**
     * app端获取定位后上传位置信息  即经纬度信息
     */
    @GetMapping("/updateStationLocation")
    @CrossOrigin
    public AjaxResult updateStationLocation(VStation vStation){
        AjaxResult ajaxResult = AjaxResult.success();
        int i=ivStationService.updateVStationByID(vStation);
        if (i>0){
            return ajaxResult.success("上传成功");
        }else {
            return ajaxResult.error("上传失败");
        }

    }


    /**
     * app端根据站点id获取该站点的基本信息
     */
    @GetMapping("/getVstationmodel")
    @CrossOrigin
    public AjaxResult getVstationmodel(VStation vStation){
        AjaxResult ajaxResult = AjaxResult.success();
        vStation=ivStationService.selectVStationById(vStation.getId());
        AttendanceRecord attendanceRecord=new AttendanceRecord();
        attendanceRecord.setStationcode(vStation.getStationcode());
        List<AttendanceRecord> attendanceRecordList=attendanceRecordService.selecAttendanceRecordByStationCode(attendanceRecord);
        ajaxResult.put("vStation", vStation);
        ajaxResult.put("attendanceRecordList", attendanceRecordList);
        return ajaxResult;
    }

    /**
     * 根据站点生成站点记录信息，或者回显上次巡检记录
     */
    @GetMapping("/getUserInspectClassify")
    public AjaxResult getUserInspect(@RequestParam Long stationId){
        List<InspectRecordVO> inspectRecordVOs = inspectRecordService.getUserInspect(stationId,SecurityUtils.getLoginUser().getUser().getUserId());
        return AjaxResult.success(inspectRecordVOs);
    }

    /**
     * 根据站点生成站点记录信息，或者回显上次巡检记录
     */
    @GetMapping("/getInspectItems")
    public AjaxResult getUserInspect(@RequestParam Long classifyId,@RequestParam Long inspectRecordId){
        List<InspectItemRecordVO> inspectItems = iInspectItemService.getInspectItemsByClassifyAndRecordId(classifyId,inspectRecordId);
        return AjaxResult.success(inspectItems);
    }

    /**
     * 根据站点生成站点记录信息，或者回显上次巡检记录
     */
    @PostMapping("/saveInspectItems")
    public AjaxResult saveInspectItems(@RequestBody InspectItemRecordVO inspectItemRecordVO){
        Optional.ofNullable(inspectItemRecordVO.getInspectRecordId()).orElseThrow(()->new BaseException("参数异常"));
        int i = iInspectItemService.saveInspectItems(inspectItemRecordVO);
        return AjaxResult.success(i);
    }

    /**
     * 巡检记录
     */
    @PostMapping("/getUserInspectRecord")
    public AjaxResult getUserInspectRecord(@RequestBody InspectRecordQuery inspectRecordQuery){
        PageInfo<InspectRecordVO> inspectRecordPageInfo = inspectRecordService.getUserInspectRecord(inspectRecordQuery);
        return AjaxResult.success(inspectRecordPageInfo);
    }

    @PostMapping("/saveItemRecordPic")
    public AjaxResult saveItemRecordPic(@RequestParam("file") MultipartFile file,@RequestParam("inspectItemRecordId") Long inspectItemRecordId) throws IOException
    {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
            //更新巡检项记录的图片
            ItemRecordPic itemRecordPic = new ItemRecordPic();
            itemRecordPic.setItemRecordId(inspectItemRecordId);
            itemRecordPic.setFilePath(avatar);
            iItemRecordPicService.insertItemRecordPic(itemRecordPic);
//            AjaxResult ajaxResult = new AjaxResult();
//            ajaxResult.put("url",avatar);
            return AjaxResult.success(avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 根据详情记录查询巡检记录详情(分页)
     */
    @PostMapping("/getUserInspectRecordItemList")
    public AjaxResult getUserInspectRecordItemList(@RequestBody InspectRecordQuery inspectRecordQuery){
        Optional.ofNullable(inspectRecordQuery.getInspectRecordId()).orElseThrow(()->new BaseException("参数缺失"));
//        PageInfo<InspectRecordVO> inspectRecordPageInfo = inspectRecordService.getUserInspectRecord(inspectRecordQuery);
        PageHelper.startPage(inspectRecordQuery.getPageNum(),inspectRecordQuery.getPageSize());
        List<InspectItemRecordVO> inspectRecordPageInfo = iInspectItemRecordService.getUserInspectRecordItemList(inspectRecordQuery);
        return AjaxResult.success(new PageInfo<>(inspectRecordPageInfo));
    }


    /**
     * app端根据工单主键id修改工单的状态
     */
    @PostMapping("/updateWorkOrderStatus")
    public AjaxResult updateWorkOrder(@RequestBody WorkOrder workOrder){
        Optional.ofNullable(workOrder.getId()).orElseThrow(()->new BaseException("参数异常"));
        return AjaxResult.success(iWorkOrderService.updateWorkOrderStatus(workOrder));
    }

    /**
     * app端根据工单主键id修改工单的状态
     */
    @PostMapping("/appSeedWorkOrder")
    public AjaxResult appSeedWorkOrder(@RequestBody WorkOrder workOrder){
        return AjaxResult.success(iWorkOrderService.appSeedWorkOrder(workOrder));
    }

    /**
     * 获取区域下拉树列表(带站点)
     */
    @GetMapping("/appStationTree")
//    public AjaxResult treeStationselect(SysArea area)
    public AjaxResult treeStationselect(CStation cStation)
    {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        area.setUserId(loginUser.getUser().getUserId());
//        List<SysAreaStation> areas = areaService.selectAreaAndStationList(area);
//        return AjaxResult.success(areaService.buildAreaStationTreeSelect(areas));
        List<SysNode> sysNodes = cStationService.stationTree(cStation);
        return AjaxResult.success(treeUtils.buildTreeSelect(sysNodes));
    }

    /**
     * 获取区域下拉树列表(带站点)
     */
    @GetMapping("/appWorkOrderExecutor")
    public AjaxResult appWorkOrderExecutor(SysUser sysUser)
    {
        return AjaxResult.success(iSysUserService.selectUserList(sysUser));
    }


}
